package com.example.hlddz2.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.example.hlddz2.R;
import com.example.hlddz2.databinding.FragmentHomeBinding;
import com.example.hlddz2.model.NavItem;
import com.example.hlddz2.model.Product;
import com.example.hlddz2.network.ApiService;
import com.example.hlddz2.repository.ProductRepository;
import com.example.hlddz2.viewmodel.HomeViewModel;
import com.example.hlddz2.ui.activity.ProductDetailActivity;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class HomeFragment extends Fragment {

    private List<Product> allProducts = new ArrayList<>(); // 保存所有商品
    private List<Product> filteredProducts = new ArrayList<>(); // 保存过滤后的商品

    private FragmentHomeBinding binding;
    private HomeViewModel viewModel;
    private NavItemAdapter navItemAdapter;
    private ProductAdapter productAdapter;
    // 新增：搜索相关变量
    private EditText etSearch;
    private Button btnSearch;
    private TextView tvListTitle;
    private String currentSearchQuery = "";

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        RecyclerView navRecyclerView = binding.navRecyclerView;
        RecyclerView goodsRecyclerView = binding.goodsRecyclerView;
        SwipeRefreshLayout swipeRefreshLayout = binding.swipeRefresh;

        etSearch = root.findViewById(R.id.et_search);
        btnSearch = root.findViewById(R.id.btn_search);
        tvListTitle = root.findViewById(R.id.tv_list_title);

        navItemAdapter = new NavItemAdapter();
        productAdapter = new ProductAdapter();

        navRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        navRecyclerView.setAdapter(navItemAdapter);

        goodsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        goodsRecyclerView.setAdapter(productAdapter);

        productAdapter.setOnProductClickListener(product -> {
            android.content.Intent intent = new android.content.Intent(getContext(), ProductDetailActivity.class);
            intent.putExtra(ProductDetailActivity.EXTRA_GOODS_ID, product.getGoods_id());
            startActivity(intent);
        });

        // 初始化 Retrofit
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(logging)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api-hmugo-web.itheima.net/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        ApiService apiService = retrofit.create(ApiService.class);
        ProductRepository repository = new ProductRepository(apiService);
        viewModel = new ViewModelProvider(this, new ViewModelProvider.Factory() {
            @NonNull
            @Override
            public <T extends androidx.lifecycle.ViewModel> T create(@NonNull Class<T> modelClass) {
                return (T) new HomeViewModel(repository);
            }
        }).get(HomeViewModel.class);

        // 观察导航数据
        viewModel.getNavItems().observe(getViewLifecycleOwner(), navItems -> {
            if (navItems != null) {
                // 对导航项进行去重处理
                List<NavItem> distinctNavItems = removeDuplicateNavItems(navItems);
                navItemAdapter.setNavItems(distinctNavItems);

                Log.d("HomeFragment", "原始导航项数量: " + navItems.size());
                Log.d("HomeFragment", "去重后导航项数量: " + distinctNavItems.size());

                for (NavItem item : distinctNavItems) {
                    Log.d("HomeFragment", "导航项: " + item.getName());
                }
            } else {
                Log.e("HomeFragment", "Nav items is null");
            }
        });

        // 观察商品数据
        viewModel.getGoodsList().observe(getViewLifecycleOwner(), products -> {
            if (products != null) {
                productAdapter.setProducts(products);
                // 更新列表标题
                updateListTitle();
            } else {
                Log.e("HomeFragment", "Products is null");
            }
            swipeRefreshLayout.setRefreshing(false);
        });
        // 新增：设置搜索按钮点击事件
        btnSearch.setOnClickListener(v -> {
            performSearch();
        });

        // 新增：设置键盘搜索按钮事件
        etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                performSearch();
                return true;
            }
            return false;
        });


        // 下拉刷新
        swipeRefreshLayout.setOnRefreshListener(() -> {
            viewModel.loadNavItems();
            // 刷新时保持当前搜索状态
            if (currentSearchQuery.isEmpty()) {
                viewModel.loadGoodsList("", 0, 10, 1);
            } else {
                viewModel.loadGoodsList(currentSearchQuery, 0, 10, 1);
            }
        });

        // 加载数据
        viewModel.loadNavItems();
        viewModel.loadGoodsList("", 0, 10, 1);

        return root;


    }

    // 新增：执行搜索的方法
    private void performSearch() {
        String query = etSearch.getText().toString().trim();
        currentSearchQuery = query;

        // 隐藏软键盘
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);

        // 显示加载状态
        binding.swipeRefresh.setRefreshing(true);



        Log.d("HomeFragment", "=== 搜索调试信息 ===");
        Log.d("HomeFragment", "搜索关键词: " + query);
        Log.d("HomeFragment", "调用API: getGoodsList(" + query + ", 0, 10, 1)");
        // 执行搜索
        viewModel.loadGoodsList(query, 0, 10, 1);
        viewModel.getGoodsList().observe(getViewLifecycleOwner(), products -> {
            Log.d("HomeFragment", "收到商品数据: " + (products != null ? products.size() + " 个商品" : "null"));

            if (products != null && !products.isEmpty()) {
                // 打印前几个商品名称，检查是否匹配搜索词
                for (int i = 0; i < Math.min(3, products.size()); i++) {
                    Product product = products.get(i);
                    Log.d("HomeFragment", "商品 " + i + ": " + product.getGoods_name());
                }
            }

            if (products != null) {
                productAdapter.setProducts(products);
                updateListTitle();
            } else {
                Log.e("HomeFragment", "Products is null");
            }
            binding.swipeRefresh.setRefreshing(false);
        });
    }

    // 新增：更新列表标题
    private void updateListTitle() {
        if (currentSearchQuery.isEmpty()) {
            tvListTitle.setText("商品列表");
        } else {
            tvListTitle.setText("搜索结果: " + currentSearchQuery);
        }
    }

    // 新增：清空搜索
    private void clearSearch() {
        etSearch.setText("");
        currentSearchQuery = "";
        viewModel.loadGoodsList("", 0, 10, 1);
        updateListTitle();
    }
    private List<NavItem> removeDuplicateNavItems(List<NavItem> navItems) {
        if (navItems == null || navItems.isEmpty()) {
            return new ArrayList<>();
        }


        Map<String, NavItem> uniqueNavItems = new LinkedHashMap<>();

        for (NavItem item : navItems) {
            if (item != null && item.getName() != null) {
                if (uniqueNavItems.containsKey(item.getName())) {
                    Log.w("HomeFragment", "发现重复导航项，已跳过: " + item.getName());
                } else {
                    uniqueNavItems.put(item.getName(), item);
                }
            }
        }

        return new ArrayList<>(uniqueNavItems.values());
    }

    // 修改后的导航项适配器 - 隐藏TextView
    static class NavItemAdapter extends RecyclerView.Adapter<NavItemAdapter.ViewHolder> {
        private List<NavItem> navItems = new ArrayList<>();

        public void setNavItems(List<NavItem> navItems) {
            this.navItems = navItems != null ? navItems : new ArrayList<>();
            notifyDataSetChanged();

            Log.d("NavItemAdapter", "适配器中项数量: " + this.navItems.size());
            for (NavItem item : this.navItems) {
                Log.d("NavItemAdapter", "适配器中的项: " + (item != null ? item.getName() : "null"));
            }
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_nav, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            if (navItems != null && position < navItems.size()) {
                NavItem item = navItems.get(position);
                if (item != null) {
                    // 隐藏TextView，因为图片已经包含文字
                    holder.name.setVisibility(View.GONE);

                    if (item.getImage_src() != null && !item.getImage_src().isEmpty()) {
                        Glide.with(holder.itemView.getContext())
                                .load(item.getImage_src())
                                .placeholder(R.color.light_gray)
                                .into(holder.image);
                    }
                }
            }
        }

        @Override
        public int getItemCount() {
            return navItems.size();
        }

        static class ViewHolder extends RecyclerView.ViewHolder {
            ImageView image;
            TextView name;

            ViewHolder(View itemView) {
                super(itemView);
                image = itemView.findViewById(R.id.nav_image);
                name = itemView.findViewById(R.id.nav_name);
            }
        }
    }

    // 商品适配器保持不变
    static class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> {
        private List<Product> products;
        private OnProductClickListener listener;

        public void setProducts(List<Product> products) {
            this.products = products;
            notifyDataSetChanged();
        }

        public void setOnProductClickListener(OnProductClickListener l) {
            this.listener = l;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_product, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            Product product = products.get(position);
            holder.name.setText(product.getGoods_name());
            holder.price.setText("¥ " + String.valueOf(product.getGoods_price()));
            Glide.with(holder.itemView.getContext())
                    .load(product.getGoods_small_logo())
                    .placeholder(R.color.light_gray)
                    .into(holder.image);

            holder.itemView.setOnClickListener(v -> {
                if (listener != null) listener.onClick(product);
            });
        }

        @Override
        public int getItemCount() {
            return products == null ? 0 : products.size();
        }

        static class ViewHolder extends RecyclerView.ViewHolder {
            ImageView image;
            TextView name;
            TextView price;

            ViewHolder(View itemView) {
                super(itemView);
                image = itemView.findViewById(R.id.product_image);
                name = itemView.findViewById(R.id.product_name);
                price = itemView.findViewById(R.id.product_price);
            }
        }
    }

    interface OnProductClickListener {
        void onClick(Product product);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}